package com.example.demo.filters.inbound;

import com.netflix.zuul.context.Debug;
import com.netflix.zuul.context.SessionContext;
import com.netflix.zuul.filters.http.HttpInboundSyncFilter;
import com.netflix.zuul.message.http.HttpRequestMessage;

import java.util.Iterator;

/**
 * @author sleepforests
 * Created on 2019-06-27
 */
public class DebugRequest extends HttpInboundSyncFilter {
    @Override
    public int filterOrder() {
        return 21;
    }

    @Override
    public boolean shouldFilter(HttpRequestMessage request) {
        return request.getContext().debugRequest();
    }

    @Override
    public boolean needsBodyBuffered(HttpRequestMessage request) {
        return shouldFilter(request);
    }


    @Override
    public HttpRequestMessage apply(HttpRequestMessage request) {
        SessionContext ctx = request.getContext();

        Debug.addRequestDebug(ctx, "REQUEST:: " + request.getOriginalScheme() + " " + request.getOriginalHost() + ":" + request.getOriginalPort());

        Debug.addRequestDebug(ctx, "REQUEST:: > " + request.getMethod() + " " + request.reconstructURI() + " " + request.getProtocol());

        Iterator headerIt = request.getHeaders().entries().iterator();
        while (headerIt.hasNext()) {
            String name = (String) headerIt.next();
            String value = request.getHeaders().getFirst(name);
            Debug.addRequestDebug(ctx, "REQUEST:: > " + name + ":" + value);

        }

        if (request.hasBody()) {
            Debug.addRequestDebug(ctx, "REQUEST:: > " + request.getBodyAsText());
        }

        return request;
    }

}
